package com.finger.forest.http;

import android.util.Log;

import com.finger.forest.model.BaseModel;
import com.finger.forest.model.BaseNoDataModel;
import com.finger.forest.utils.ToastUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author sy
 * @date 2020/5/12
 * @desc
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody,
        T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    /**
     * 针对数据返回成功、错误不同类型字段处理
     */
    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            // 这里的type实际类型是 LoginUserEntity<User>  User就是user字段的对象。
            BaseModel result = gson.fromJson(response, BaseModel.class);
            int code = result.getCode();
            if (null == result.getRst()) {
                BaseNoDataModel errResponse = gson.fromJson(response, BaseNoDataModel.class);
                if (code == 1) {
                    return gson.fromJson(response, type);
                } else {
                    if (null != errResponse) {
                        ToastUtils.show(errResponse.getMsg() == null ? " " : errResponse.getMsg());
                    }
//                    throw new ResultException(errResponse.getMsg(), code);
                    return null;
                }
            } else {
                if (code == 1) {
                    return gson.fromJson(response, type);
                } else {
                    Log.d("HttpManager", "err==：" + response);
                    BaseNoDataModel errResponse = gson.fromJson(response, BaseNoDataModel.class);
                    if (code == 1) {
                        return gson.fromJson(response, type);
                    } else {
                        if (null != errResponse) {
                            ToastUtils.show(errResponse.getMsg() == null ? " " : errResponse.getMsg());
                        }
                        return null;
//                        throw new ResultException(errResponse.getMsg(), code);
                    }
                }
            }
        } finally {
            value.close();
        }
    }
}
